package com.sherlocky.resource.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Decoder;

public class Base642Img {
    
	
	
	/**
	 * 替换html中的base64图片数据为实际图片
	 * @param html
	 * @param fileRoot 本地路径
	 * @param serRoot 服务器路径 
	 * @example /bk/ckfile.do?path=/ueditor_upload/images/20140418163022311_0.png"
	 * @return
	 */
	
   
	public static String replaceBase64Image(String html,String fileRoot,String serRoot){
		File file = new File(fileRoot);
		html = html.replaceAll("/<!-{1,2}[\\s\\S]*?-->/", "");
		html = html.replaceAll("/\\*{1,2}[\\s\\S]*?\\*/", ""); //删除/***/ 单行或多行注释
//		html = html.replaceAll("/\\*\b\\s.*?\\*/", "");
		if(!file.exists()){
			new File(fileRoot).mkdirs();
		}
		String htmlContent = html;
		Pattern pattern = Pattern.compile("\\<img[^>]*src=\"data:image/[^>]*>");
		Matcher matcher = pattern.matcher(html);	
		while(matcher.find()){		//找出base64图片元素	
			
			String str = matcher.group();		
			String src = StringUtils.substringBetween(str, "src=\"", "\"");//src="..."
			String ext = StringUtils.defaultIfEmpty(StringUtils.substringBetween(str, "data:image/", ";"), "jpg");//图片后缀			
			String base64ImgData = StringUtils.substringBetween(str, "base64,", "\"");//图片数据
			if(StringUtils.isNotBlank(ext)&&StringUtils.isNotBlank(base64ImgData)){
				//编码的gif图片数据
				//编码的png图片数据
				if("jpeg".equalsIgnoreCase(ext)){//编码的jpeg图片数据
					ext = "jpg";
				} else if("x-icon".equalsIgnoreCase(ext)){//编码的icon图片数据
					ext = "ico";
				}
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				String fileName = uuid+"."+ext;//待存储的文件名
				String filePath = fileRoot+File.separator+fileName;//图片路径
				try {
					convertBase64DataToImage(base64ImgData, filePath);//转成文件
					String serPath = serRoot+uuid +"@"+ext;//服务器地址
					htmlContent = htmlContent.replace(src, serPath);//替换src为服务器地址
				} catch (IOException e) {
					e.printStackTrace();
				}		
			}			
		}	
//		htmlContent = htmlContent.replaceAll("\\/\\/[^\\n]*|\\/\\*([^\\*^\\/]*|[\\*^\\/*]*|[^\\**\\/]*)*\\*+\\/", "");
		return htmlContent;
	}
	/**
	 * 把base64图片数据转为本地图片
	 * @param base64ImgData
	 * @param filePath
	 * @throws IOException
	 */
	public static void convertBase64DataToImage(String base64ImgData,String filePath) throws IOException {
		BASE64Decoder d = new BASE64Decoder();
		byte[] bs = d.decodeBuffer(base64ImgData);
		FileOutputStream os = new FileOutputStream(filePath);
		os.write(bs);
		os.close();
	}
}
